// 引入MongoClinet
const { MongoClient } = require('mongodb'),
      { url, dbName} = require('./config')


// 配置
const client = new MongoClient(url)

//连接

class Db {
  static getInstance() {  /*1、单例  多次实例化实例不共享的问题*/
    if(!Db.instance) {
      Db.instance = new Db();
    }
    return Db.instance;
  }
  constructor() {
    this.dbClient='';   /*属性 放db对象*/
    this.connect()/*实例化的时候就连接数据库*/
  }
  connect() { /*连接数据库*/
    let _that = this;
    return new Promise((resolve,reject) => {
      if(!_that.dbClient) {
        client.connect(err => {
          if(err) {
            reject(err)
            return
          }
          console.log('连接成功')
          _that.dbClient = client.db(dbName)
          resolve(_that.dbClient)
        })
      }else {
        resolve(_that.dbClient)
      }
    })
  }
  close() {
    client.close()
    console.log('数据库关闭')
  }
  // 查
  find(collectionName, json='') {
    return new Promise((resolve, reject) => {
      this.connect().then(db => {
        db.collection(collectionName).find(json).toArray((err, data) => {
          if(err) {
            reject(err)
            return
          }
          resolve(data)
        })
      })
    })
  }
  // 增
  insert(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then(db => {
        db.collection(collectionName).insertOne(json, (err, data) => {
          if(err) {
            reject(err)
            return
          }
          resolve(data)
        })
      })
    })
  }
}

module.exports = Db.getInstance();

// var a = Db.getInstance()
// a.find('user').then(res => {
//   console.log(res)
// })